package com.timeDeal.servlet;

import com.timeDeal.bean.UserBean;
import com.timeDeal.service.UserService;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import static com.timeDeal.service.RandomValidateCodeService.RANDOMCODEKEY;

/**
 * Created by yong on 2016/9/8.
 */

/**
 * 用户注册
 */
public class UserZhuceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserBean user=new UserBean();
        String zhanghao= request.getParameter("zhanghao") ;
        String mima= request.getParameter("mima") ;
        response.setContentType("text/html;charset=UTF-8");
        user.setYonghuming(request.getParameter("yonghuming"));
        user.setZhanghao(request.getParameter("zhanghao"));
        user.setMima(request.getParameter("mima"));
        String  chongfumima = request.getParameter("chongfumima");
        System.out.println(chongfumima);
        System.out.println(user.getZhanghao());
        System.out.println(user.getMima());
        System.out.println(user.getYonghuming());
        UserService userService=new UserService();
        boolean result = false;
        String clientCheckcode = request.getParameter("randomCode");//接收客户端浏览器提交上来的验证码
        String serverCheckcode = (String) request.getSession().getAttribute(RANDOMCODEKEY);//从服务器端的session中取出验证码
        if (clientCheckcode.equalsIgnoreCase(serverCheckcode)) {//将客户端验证码和服务器端验证比较，如果相等，则表示验证通过
            System.out.println("验证码验证通过！");
        }else {
            System.out.println("验证码验证失败！");
            PrintWriter pw=response.getWriter();
            pw.print("<script language='javascript'>alert('验证码输入错误!不区分大小写');</script>");
            request.getRequestDispatcher("/user/reg.jsp").forward(request,response);
            return;

        }
        try {
            result = userService.doReg(user,chongfumima);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(result);
        if(result){
            PrintWriter pw=response.getWriter();
            pw.print("<script language='javascript'>alert('恭喜您注册成功');</script>");
            request.getRequestDispatcher("/user/login.jsp?zhanghao="+zhanghao+"&mima="+mima).forward(request,response);
        }
        else{
            PrintWriter pw=response.getWriter();
            pw.print("<script language='javascript'>alert('注册失败');</script>");
            request.getRequestDispatcher("/user/reg.jsp").forward(request,response);
        }
   }

}
